package com.damai.plugins.impl;

import java.io.IOException;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.citywithincity.cache.CacheUtil;
import com.citywithincity.cache.XMemcached;
import com.citywithincity.utils.ConfigReader;
import com.citywithincity.utils.MD5Util;
import com.damai.plugins.IPlugin;

public class MemcachePlugin implements IPlugin {
	
	private static Log logger = LogFactory.getLog(MemcachePlugin.class);
	
	// server list and weights
	String[] servers = { "localhost:11211" };

	Integer[] weights = { 1 };
	
	private XMemcached memcached;
	
	public MemcachePlugin() {
		
	}

	@Override
	public void start() {
		try {
			ConfigReader reader = ConfigReader.getReader("memcached.properties");
			servers = reader.get("memcached-servers", "").split(",");
			String[] arr = reader.get("memcached-weights", "").split(",");
			weights = new Integer[arr.length];
			int index=0;
			for (String string : arr) {
				weights[index++] = Integer.parseInt(string);
			}
	
		} catch (IOException e) {
			logger.warn("The config file memcached-[x].properties not found, memcached is not init");
			return;
		} 
	
		memcached = new XMemcached(servers[0]);
		CacheUtil.setCache(memcached);
		String key = MD5Util.md5Appkey(String.valueOf(System.currentTimeMillis()));
		CacheUtil.set(key, key);
		String value = CacheUtil.get(key);
		if(value==null){
			throw new RuntimeException("Memcached 未启动成功");
		}
		CacheUtil.delete(key);
	}

	@Override
	public void stop() {
		if(memcached!=null){
			memcached.shutdown();
			memcached = null;
		}
	}

}
